import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useCounterStore = defineStore('counter', () => {
    const cartList = ref([])
    const addressList = ref([{
        id: '1',
        name: '张三',
        tel: '13000000000',
        address: '浙江省杭州市西湖区文三路 138 号东方通信大厦 7 楼 501 室',
        isChecked: true, // 当前选中的地址
    },
    {
        id: '2',
        name: '李四',
        tel: '1310000000',
        address: '浙江省杭州市拱墅区莫干山路 50 号',
        isChecked: false,
    },
    {
        id: '3',
        name: '王五',
        tel: '1310000000',
        address: '上海市奉贤区',
        isChecked: false,
    }])
    const myorderList = ref([])  // 我的订单列表
    const totalCount = computed(() => {
        return cartList.value.reduce((sum, item) => sum + item.count, 0)
    })
    const totalPrice = computed(() => {
        return cartList.value.reduce((sum, item) => item.checked ? sum + item.count * item.price * 100 : sum, 0)
    })
    // 获取选中的地址
    const checkedAddress = computed(() => {
        return addressList.value.find(item => item.isChecked)
    })
    // 确认订单列表
    const orderList = computed(() => {
        return cartList.value.filter(item => item.checked == true)
    })
    // 将商品添加到购物车
    const addItem = (payload) => {
        const index = cartList.value.findIndex(item => item.id == payload.id)
        if (index > -1) {
            cartList.value[index].count++
        } else {
            cartList.value.push({
                ...payload,
                count: 1,
                checked: false
            })
        }
    }
    // 删除购物车的商品
    const deleteItem = (id) => {
        cartList.value = cartList.value.filter(item => item.id != id)
    }
    // 修改商品数量
    const updateCount = (id, count) => {
        cartList.value.find(item => item.id == id).count = count
    }
    // 切换地址 
    const changeisChecked = (id) => {
        addressList.value.forEach(item => {
            item.isChecked = false
            if (item.id == id) {
                item.isChecked = true
            }
        })
    }
    // 将订单添加到订单列表中
    const addmyOrder = (payload) => {
        myorderList.value.push(payload)
    }
    // 修改传过来的id对应订单的状态-- 从待付款 1 修改为待发货 2
    const updateOrderStatus = (id) => {
        myorderList.value.find(item => item.id == id).status = 2
    }
    return { cartList, addressList, myorderList, totalCount, totalPrice, checkedAddress, orderList, addItem, deleteItem, updateCount, changeisChecked, addmyOrder, updateOrderStatus }
}, {
    persist: true,
})